package com.example.pathtracker.activity

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapsInitializer
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.maps.model.PolylineOptions
import com.example.pathtracker.R
import com.example.pathtracker.bean.PathData
import com.example.pathtracker.bean.PathTypeData
import com.example.pathtracker.bean.Point
import com.example.pathtracker.bean.UploadResponse
import com.example.pathtracker.databinding.ActivityMapBinding
import com.example.pathtracker.net.RetrofitClient
import com.example.pathtracker.service.LocationService
import com.example.pathtracker.utils.LocationManager
import com.example.pathtracker.utils.LocationUtils
import com.example.pathtracker.utils.NetworkUtils
import com.example.pathtracker.utils.SPUtils
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.Collections

class MapActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMapBinding
    private lateinit var aMap: AMap
    private lateinit var locationManager: LocationManager
    private var isTracking = false
    private var polyline: PolylineOptions? = null
    private var currentPathType: PathTypeData? = null
    private var pathTypeList: List<PathTypeData> = emptyList()
    private var unsubmittedDialog: AlertDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        MapsInitializer.updatePrivacyShow(this, true, true)
        MapsInitializer.updatePrivacyAgree(this, true)

        binding = ActivityMapBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.title = "路径采集"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        try {
            binding.mapView.onCreate(savedInstanceState)
            aMap = binding.mapView.map
            setupMap()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "地图初始化失败: ${e.message}", Toast.LENGTH_LONG).show()
        }

        checkPermissions()
        initLocationManager()

        binding.startButton.setOnClickListener {
            showPathTypeDialog()
        }

        binding.stopButton.setOnClickListener {
            showStopTrackingDialog()
        }

        getPathType()

        val fab = findViewById<FloatingActionButton>(R.id.fab_unsubmitted)
        fab.setOnClickListener { showUnsubmittedDialog() }

    }

    private fun getPathType() {
        Log.d("MapActivity", "开始网络请求 getAllPathType...")
        Log.d("MapActivity", "BASE_URL: http://192.168.31.68:8080/usermergeserver/server/")

        // 检查网络状态
        if (!NetworkUtils.isNetworkAvailable(this)) {
            Log.e("MapActivity", "网络不可用")
            Toast.makeText(this, "网络连接不可用,使用默认路径类型", Toast.LENGTH_SHORT).show()
            useDefaultPathTypes()

            return
        }

        // 记录网络信息
        NetworkUtils.logNetworkInfo(this)

        RetrofitClient.apiService.getAllPathType().enqueue(object : Callback<UploadResponse<List<PathTypeData>>> {
            override fun onResponse(
                call: Call<UploadResponse<List<PathTypeData>>>,
                response: Response<UploadResponse<List<PathTypeData>>>
            ) {
                Log.d("MapActivity", "网络请求成功，状态码: ${response.code()}")
                Log.d("MapActivity", "响应体: ${response.body()}")
                if (response.isSuccessful) {
                    response.body()?.let { uploadResponse ->
                        Log.d("MapActivity", "成功获取路径类型: ${uploadResponse.data}")
                        uploadResponse.data?.let { types ->
                            pathTypeList = types
                            Log.d("MapActivity", "保存了 ${types.size} 个路线类型")
                            SPUtils.put(this@MapActivity, "pathTypeList", types)
                        }
                    }
                } else {
                    Log.e("MapActivity", "服务器错误: ${response.code()} - ${response.message()}")
                    // 如果网络请求失败，使用默认的枚举类型
                    useDefaultPathTypes()
                }
            }

            override fun onFailure(call: Call<UploadResponse<List<PathTypeData>>>, t: Throwable) {
                Log.e("MapActivity", "网络请求失败", t)
                Log.e("MapActivity", "错误信息: ${t.message}")
                Log.e("MapActivity", "错误类型: ${t.javaClass.simpleName}")
                // 如果网络请求失败，使用默认的枚举类型
                useDefaultPathTypes()
            }
        })
    }

    private fun useDefaultPathTypes() {
        Log.d("MapActivity", "使用默认路线类型")
        val type = object : TypeToken<List<PathTypeData>>() {}.type
        pathTypeList= SPUtils.getObject(this, "pathTypeList", type)
        if(pathTypeList.isEmpty() ){
            pathTypeList = listOf(
                PathTypeData(1, "人行道", "SIDEWALK", "#00FF00"),
                PathTypeData(2, "汽车道", "VEHICLE_ROAD", "#0000FF"),
                PathTypeData(3, "摩托车道", "MOTORCYCLE_LANE", "#FFFF00"),
                PathTypeData(4, "消防车道", "FIRE_LANE", "#FF0000")
            )
        }

    }

    private fun setupMap() {
        try {
            val myLocationStyle = MyLocationStyle()
                .interval(2000)
                .showMyLocation(true)
                .myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE)
            
            aMap.apply {
                setMyLocationStyle(myLocationStyle)
                isMyLocationEnabled = true
                uiSettings.isMyLocationButtonEnabled = true
                uiSettings.isZoomControlsEnabled = true
                mapType = AMap.MAP_TYPE_NORMAL
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "地图设置失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }

    private fun checkPermissions() {
        val permissions = arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WAKE_LOCK,
            Manifest.permission.FOREGROUND_SERVICE,
            Manifest.permission.FOREGROUND_SERVICE_LOCATION,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE
        )

        val permissionsToRequest = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }.toTypedArray()

        if (permissionsToRequest.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissionsToRequest, PERMISSION_REQUEST_CODE)
        }
        
        // 检查网络状态
//        checkNetworkStatus()
    }
    
    private fun checkNetworkStatus() {
        val connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as android.net.ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        val isConnected = networkInfo?.isConnected == true
        
        Log.d("MapActivity", "网络连接状态: $isConnected")
        if (!isConnected) {
            Toast.makeText(this, "网络连接不可用", Toast.LENGTH_SHORT).show()
        }
    }

    private fun initLocationManager() {
        locationManager = LocationManager.getInstance(this)
        locationManager.initLocation()
        
        // 设置更高的位置更新频率
        locationManager.setLocationInterval(1000L)  // 1秒更新一次
        locationManager.setLocationFastestInterval(500L)  // 最快500毫秒更新一次
        
        // 设置位置更新监听器
        locationManager.setOnLocationUpdateListener { location ->
            if (location != null) {
                updateLocationInfo(location)
                try {
                    val latLng = LatLng(location.latitude, location.longitude)
                    // 只在开始跟踪时才自动移动相机
                    if (isTracking) {
                        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17f))
                    }
                } catch (e: Exception) {
                    Log.e("MapActivity", "Camera update failed", e)
                }
            }
        }
        
        // 设置路径更新监听器
        locationManager.setOnPathUpdateListener { pathPoints ->
            if (pathPoints.isNotEmpty()) {
                android.util.Log.d("MapActivity", "收到路径更新: ${pathPoints.size}个点")
                drawPath(pathPoints)
            }
        }
        
        // 立即请求一次位置更新
        locationManager.requestSingleUpdate()
    }

    private fun showPathTypeDialog() {
        if (pathTypeList.isEmpty()) {
            Toast.makeText(this, "正在加载路线类型，请稍后重试", Toast.LENGTH_SHORT).show()
            return
        }

        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_path_type_selection, null)
        val recyclerView = dialogView.findViewById<RecyclerView>(R.id.rv_path_types)
        val btnCancel = dialogView.findViewById<Button>(R.id.btn_cancel)
        
        recyclerView.layoutManager = LinearLayoutManager(this)
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()
        recyclerView.adapter = PathTypeAdapter(pathTypeList) { selectedType ->
            currentPathType = selectedType
            startTracking()
            dialog.dismiss()
        }
        
        btnCancel.setOnClickListener {
            dialog.dismiss()
        }
        

        dialog.show()
    }

    inner class PathTypeAdapter(
        private val types: List<PathTypeData>,
        private val onTypeSelected: (PathTypeData) -> Unit
    ) : RecyclerView.Adapter<PathTypeAdapter.ViewHolder>() {
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_path_type, parent, false)
            return ViewHolder(view)
        }
        
        override fun getItemCount(): Int = types.size
        
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bind(types[position])
        }
        
        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val colorIndicator: View = itemView.findViewById(R.id.color_indicator)
            private val tvTypeName: TextView = itemView.findViewById(R.id.tv_type_name)
            
            fun bind(pathType: PathTypeData) {
                tvTypeName.text = pathType.typeName
                
                // 设置颜色指示器
                try {
                    val color = android.graphics.Color.parseColor(pathType.lineColor ?: "#0000FF")
                    colorIndicator.setBackgroundColor(color)
                } catch (e: Exception) {
                    colorIndicator.setBackgroundColor(android.graphics.Color.BLUE)
                }
                
                itemView.setOnClickListener {
                    onTypeSelected(pathType)
                }
            }
        }
    }

    private fun showStopTrackingDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_stop_tracking, null)
        val btnSaveAndSubmit = dialogView.findViewById<Button>(R.id.btn_save_and_submit)
        val btnContinue = dialogView.findViewById<Button>(R.id.btn_continue)
        val btnDiscard = dialogView.findViewById<Button>(R.id.btn_discard)
        
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .setCancelable(false)
            .create()
        
        btnSaveAndSubmit.setOnClickListener {
            dialog.dismiss()
            showNameInputDialog()
        }
        
        btnContinue.setOnClickListener {
            dialog.dismiss()
            // 继续绘制，不做任何操作
        }
        
        btnDiscard.setOnClickListener {
            dialog.dismiss()
            discardTracking()
        }
        
        dialog.show()
    }

    private fun showNameInputDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_path_name_input, null)
        val nameInput = dialogView.findViewById<EditText>(R.id.et_path_name)
        val btnCancel = dialogView.findViewById<Button>(R.id.btn_cancel)
        val btnConfirm = dialogView.findViewById<Button>(R.id.btn_confirm)
        
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()
        
        btnCancel.setOnClickListener {
            dialog.dismiss()
            showStopTrackingDialog()
        }
        
        btnConfirm.setOnClickListener {
            val name = nameInput.text.toString().trim()
            if (TextUtils.isEmpty(name)) {
                Toast.makeText(this, "路径名称不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            dialog.dismiss()
            stopTracking()
            uploadPath(name)
        }
        
        dialog.show()
    }

    private fun startTracking() {
        try {
            // 先清理地图和状态
            aMap.clear()
            isTracking = true
            binding.startButton.isEnabled = false
            binding.stopButton.isEnabled = true
            
            // 确保位置管理器已经初始化
            if (!locationManager.isInitialized()) {
                locationManager.initLocation()
            }
            
            // 先开始位置跟踪
            locationManager.startTracking()
            
            // 然后启动前台服务
            LocationService.startService(this)
            
            val color = currentPathType?.lineColor?.let { parseColor(it) } ?: Color.BLUE
            polyline = PolylineOptions()
                .width(10f)
                .color(color)
            
            Toast.makeText(this, "开始记录${currentPathType?.typeName}路径", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.e("MapActivity", "启动跟踪失败", e)
            Toast.makeText(this, "启动跟踪失败: ${e.message}", Toast.LENGTH_SHORT).show()
            stopTracking()
        }
    }

    private fun parseColor(colorString: String): Int {
        return try {
            android.graphics.Color.parseColor(colorString)
        } catch (e: Exception) {
            Log.e("MapActivity", "颜色解析失败: $colorString", e)
            Color.BLUE
        }
    }

    private fun stopTracking() {
        isTracking = false
        binding.startButton.isEnabled = true
        binding.stopButton.isEnabled = false
        
        // 停止前台服务
        LocationService.stopService(this)
        
        // 停止位置跟踪
        locationManager.stopTracking()
    }

    private fun discardTracking() {
        stopTracking()
        locationManager.clearPath()
        try {
            aMap.clear()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        Toast.makeText(this, "已放弃记录", Toast.LENGTH_SHORT).show()
    }

    private fun drawPath(pathPoints: List<LatLng>) {
        if (pathPoints.size >= 2 && isTracking) {
            try {
                // 清除之前的路径线，但保留其他地图元素
                aMap.clear()
                
                // 重新创建polyline并添加所有点
                val color = currentPathType?.lineColor?.let { parseColor(it) } ?: Color.BLUE
                val newPolyline = PolylineOptions()
                    .addAll(pathPoints)
                    .width(15f)
                    .color(color)
                    .zIndex(1f)  // 确保路径线在最上层
                
                aMap.addPolyline(newPolyline)
                polyline = newPolyline
                
                // 确保最后一个点可见
                val lastPoint = pathPoints.last()
                aMap.animateCamera(CameraUpdateFactory.newLatLng(lastPoint))
            } catch (e: Exception) {
                Log.e("MapActivity", "绘制路径失败", e)
            }
        }
    }

    private fun updateLocationInfo(location: AMapLocation) {
        val info = """
            当前位置: ${location.address}
            经度: ${location.longitude}
            纬度: ${location.latitude}
            精度: ${location.accuracy}米
            速度: ${LocationUtils.formatSpeed(location.speed)}km/h
            已记录点数: ${locationManager.getPathPoints().size}
            当前路线类型: ${currentPathType?.typeName ?: "未选择"}
        """.trimIndent()
        binding.locationInfoText.text = info
    }

    private fun uploadPath(name: String) {
        val pathPoints = locationManager.getPathPoints()
        if (pathPoints.isEmpty()) {
            Toast.makeText(this, "没有采集到路径数据", Toast.LENGTH_SHORT).show()
            return
        }

        val coordinates = pathPoints.map { point ->
            doubleArrayOf(point.longitude, point.latitude)
        }.toTypedArray()

        val jsonString = Gson().toJson(coordinates)
        val pathData = PathData(
            latlon = jsonString,
            typeId = currentPathType?.id?.toString() ?: "0",
            pathName = name
        )

        if (!NetworkUtils.isNetworkAvailable(this)) {
            Log.e("MapActivity", "网络不可用")
            Toast.makeText(this, "网络连接不可用,数据将存储本地，等待联网上传", Toast.LENGTH_SHORT).show()

            // 使用sp存储
            val type = object : TypeToken<MutableList<PathData>>() {}.type
            val list: MutableList<PathData> = SPUtils.getObject(this, "path_data", type) ?: mutableListOf()
            list.add(pathData)
            SPUtils.put(this, "path_data", list)

            try {
                aMap.clear()
                binding.locationInfoText.text = ""
                locationManager.clearPath()
            } catch (e: Exception) {
                Log.e("MapActivity", "清除地图状态失败", e)
            }
            return
        }


        RetrofitClient.apiService.uploadPath(pathData).enqueue(object : Callback<UploadResponse<Unit>> {
            override fun onResponse(
                call: Call<UploadResponse<Unit>>,
                response: Response<UploadResponse<Unit>>
            ) {
                if (response.isSuccessful && response.body()?.code == 200) {
                    Toast.makeText(this@MapActivity, "路径保存成功", Toast.LENGTH_SHORT).show()
                    try {
                        aMap.clear()
                        binding.locationInfoText.text = ""
                        locationManager.clearPath()
                    } catch (e: Exception) {
                        Log.e("MapActivity", "清除地图状态失败", e)
                    }
                } else {
                    Toast.makeText(this@MapActivity, "保存路径失败", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<UploadResponse<Unit>>, t: Throwable) {
                Toast.makeText(this@MapActivity, "保存路径失败: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun showUnsubmittedDialog() {
        // 先关闭现有对话框
        unsubmittedDialog?.dismiss()
        unsubmittedDialog = null
        
        val type = object : TypeToken<List<PathData>>() {}.type
        val list: MutableList<PathData> = SPUtils.getObject(this, "path_data", type) ?: mutableListOf()

        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_unsubmitted_paths, null)
        val titleView = dialogView.findViewById<TextView>(R.id.tv_title)
        val recyclerView = dialogView.findViewById<RecyclerView>(R.id.rv_paths)
        val btnClose = dialogView.findViewById<Button>(R.id.btn_close)
        val btnUploadAll = dialogView.findViewById<Button>(R.id.btn_upload_all)
        
        if (list.isEmpty()) {
            titleView.text = "未提交路径"
            recyclerView.visibility = View.GONE
            btnUploadAll.visibility = View.GONE
            // 显示暂无数据的提示
            val emptyView = TextView(this).apply {
                text = "暂无未提交的路径数据"
                gravity = android.view.Gravity.CENTER
                setPadding(0, 40, 0, 40)
                setTextColor(android.graphics.Color.parseColor("#666666"))
            }
            (dialogView as android.widget.LinearLayout).addView(emptyView, 2)
        } else {
            titleView.text = "未提交路径 (${list.size}个)"
            recyclerView.visibility = View.VISIBLE
            btnUploadAll.visibility = View.VISIBLE
            
            recyclerView.layoutManager = LinearLayoutManager(this)
            recyclerView.adapter = UnsubmittedPathsAdapter(list) { pathData ->
                uploadPathFromDialog(pathData) {

                    // 延迟刷新，确保数据更新完成
                    runOnUiThread {
                        refreshUnsubmittedDialog()
                    }
                }
            }
        }
        
        btnClose.setOnClickListener {
            unsubmittedDialog?.dismiss()
            unsubmittedDialog = null
        }
        
        btnUploadAll.setOnClickListener {
            uploadAllPaths(list)
        }
        
        unsubmittedDialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()
        unsubmittedDialog?.show()
    }

    private fun uploadAllPaths(paths: List<PathData>) {
        if (paths.isEmpty()) {
            Toast.makeText(this, "没有可上传的路径", Toast.LENGTH_SHORT).show()
            return
        }
        
        val pathsToUpload = paths.toList() // 创建副本避免并发修改
        var uploadedCount = 0
        val totalCount = pathsToUpload.size
        
        pathsToUpload.forEach { pathData ->
            uploadPathFromDialog(pathData) {
                uploadedCount++
                if (uploadedCount == totalCount) {
                    Toast.makeText(this, "全部路径上传完成", Toast.LENGTH_SHORT).show()

                    // 强制刷新界面
                    runOnUiThread {
                        refreshUnsubmittedDialog()
                    }
                }
            }
        }
    }

    inner class UnsubmittedPathsAdapter(
        private val paths: List<PathData>,
        private val onUploadClick: (PathData) -> Unit
    ) : RecyclerView.Adapter<UnsubmittedPathsAdapter.ViewHolder>() {
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_unsubmitted_path, parent, false)
            return ViewHolder(view)
        }
        
        override fun getItemCount(): Int = paths.size
        
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bind(paths[position])
        }
        
        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val tvPathName: TextView = itemView.findViewById(R.id.tv_path_name)
            private val tvPathType: TextView = itemView.findViewById(R.id.tv_path_type)
            private val tvCoordinatesCount: TextView = itemView.findViewById(R.id.tv_coordinates_count)
            private val tvCreateTime: TextView = itemView.findViewById(R.id.tv_create_time)
            private val btnSubmit: Button = itemView.findViewById(R.id.btn_submit)
            
            fun bind(pathData: PathData) {
                tvPathName.text = pathData.pathName ?: "未命名路径"
                
                // 根据typeId获取类型名称
                val typeName = pathTypeList.find { it.id.toString() == pathData.typeId }?.typeName ?: "未知类型"
                tvPathType.text = "类型: $typeName"
                
                // 计算坐标点数
                try {
                    val coordinates = Gson().fromJson(pathData.latlon, Array<DoubleArray>::class.java)
                    tvCoordinatesCount.text = "坐标点数: ${coordinates?.size ?: 0}"
                } catch (e: Exception) {
                    tvCoordinatesCount.text = "坐标点数: 未知"
                }
                
                // 显示创建时间（这里用当前时间，实际项目中可以添加时间字段）
                tvCreateTime.text = "创建时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault()).format(java.util.Date())}"
                
                btnSubmit.setOnClickListener {
                    onUploadClick(pathData)
                }
            }
        }
    }

    private fun refreshUnsubmittedDialog() {
        // 重新创建对话框
        showUnsubmittedDialog()
    }

    private fun uploadPathFromDialog(pathData: PathData, onSuccess: () -> Unit) {
        RetrofitClient.apiService.uploadPath(pathData).enqueue(object : Callback<UploadResponse<Unit>> {
            override fun onResponse(
                call: Call<UploadResponse<Unit>>,
                response: Response<UploadResponse<Unit>>
            ) {
                if (response.isSuccessful && response.body()?.code == 200) {
                    Toast.makeText(this@MapActivity, "上传成功", Toast.LENGTH_SHORT).show()
                    removePathDataFromLocal(pathData)
                    onSuccess()
                } else {
                    Toast.makeText(this@MapActivity, "上传失败", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<UploadResponse<Unit>>, t: Throwable) {
                Toast.makeText(this@MapActivity, "上传失败: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun removePathDataFromLocal(pathData: PathData) {
        val type = object : TypeToken<List<PathData>>() {}.type
        val list: MutableList<PathData> = SPUtils.getObject(this, "path_data", type) ?: mutableListOf()
        list.removeAll { it.pathName == pathData.pathName && it.typeId == pathData.typeId && it.latlon == pathData.latlon }
        SPUtils.put(this, "path_data", list)
    }

    override fun onResume() {
        super.onResume()
        binding.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        binding.mapView.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.mapView.onDestroy()
        locationManager.destroy()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.mapView.onSaveInstanceState(outState)
    }
    override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            onBackPressedDispatcher.onBackPressed()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
    companion object {
        private const val PERMISSION_REQUEST_CODE = 100
    }
} 